package com.zoshine.zzg.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.zoshine.zzg.config.ProjectConfig;
import com.zoshine.zzg.dao.*;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.exception.SysException;
import com.zoshine.zzg.pojo.*;
import com.zoshine.zzg.pojo.pojostatus.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 导入导出服务
 *
 * @author 贾俊峰
 * @time 2017/7/28 14:50
 */
@Service
public class ImportExportService extends BaseService<ImportExport> {
    private GoodsTypeDao goodsTypeDao;
    private ProjectConfig projectConfig;
    private SystemParamService systemParamService;
    private ImportExportDao importExportDao;
    private OrganizationDao organizationDao;
    private GoodsPublishDetailDao goodsPublishDetailDao;
    private InvoiceDao invoiceDao;
    private InvoiceDetailDao invoiceDetailDao;
    private RelationSupplierPrisonDao relationSupplierPrisonDao;
    private OrderSupplierDao orderSupplierDao;
    private OrderSupplierDetailDao orderSupplierDetailDao;
    private GoodsReturnDao goodsReturnDao;
    private GoodsHistoryDetailDao goodsHistoryDetailDao;
    private PrisonerCapitalFlowDao prisonerCapitalFlowDao;
    private PrisonerAccountDao prisonerAccountDao;
    private PrisonerBasicDao prisonerBasicDao;
    private FlowTypeDao flowTypeDao;
    private PrisonerInfoDao prisonerInfoDao;
    @Autowired
    public void setGoodsTypeDao(GoodsTypeDao goodsTypeDao) {
        this.goodsTypeDao = goodsTypeDao;
    }
    @Autowired
    public void setProjectConfig(ProjectConfig projectConfig) {
        this.projectConfig = projectConfig;
    }
    @Autowired
    public void setSystemParamService(SystemParamService systemParamService) {
        this.systemParamService = systemParamService;
    }
    @Autowired
    public void setImportExportDao(ImportExportDao importExportDao) {
        this.importExportDao = importExportDao;
    }
    @Autowired
    public void setOrganizationDao(OrganizationDao organizationDao) {
        this.organizationDao = organizationDao;
    }
    @Autowired
    public void setGoodsPublishDetailDao(GoodsPublishDetailDao goodsPublishDetailDao) {
        this.goodsPublishDetailDao = goodsPublishDetailDao;
    }
    @Autowired
    public void setInvoiceDao(InvoiceDao invoiceDao) {
        this.invoiceDao = invoiceDao;
    }
    @Autowired
    public void setInvoiceDetailDao(InvoiceDetailDao invoiceDetailDao) {
        this.invoiceDetailDao = invoiceDetailDao;
    }
    @Autowired
    public void setRelationSupplierPrisonDao(RelationSupplierPrisonDao relationSupplierPrisonDao) {
        this.relationSupplierPrisonDao = relationSupplierPrisonDao;
    }
    @Autowired
    public void setOrderSupplierDao(OrderSupplierDao orderSupplierDao) {
        this.orderSupplierDao = orderSupplierDao;
    }
    @Autowired
    public void setOrderSupplierDetailDao(OrderSupplierDetailDao orderSupplierDetailDao) {
        this.orderSupplierDetailDao = orderSupplierDetailDao;
    }
    @Autowired
    public void setGoodsReturnDao(GoodsReturnDao goodsReturnDao) {
        this.goodsReturnDao = goodsReturnDao;
    }
    @Autowired
    public void setGoodsHistoryDetailDao(GoodsHistoryDetailDao goodsHistoryDetailDao) {
        this.goodsHistoryDetailDao = goodsHistoryDetailDao;
    }
    @Autowired
    public void setPrisonerCapitalFlowDao(PrisonerCapitalFlowDao prisonerCapitalFlowDao) {
        this.prisonerCapitalFlowDao = prisonerCapitalFlowDao;
    }
    @Autowired
    public void setPrisonerAccountDao(PrisonerAccountDao prisonerAccountDao) {
        this.prisonerAccountDao = prisonerAccountDao;
    }
    @Autowired
    public void setPrisonerBasicDao(PrisonerBasicDao prisonerBasicDao) {
        this.prisonerBasicDao = prisonerBasicDao;
    }
    @Autowired
    public void setFlowTypeDao(FlowTypeDao flowTypeDao) {
        this.flowTypeDao = flowTypeDao;
    }
    @Autowired
    public void setPrisonerInfoDao(PrisonerInfoDao prisonerInfoDao) {
        this.prisonerInfoDao = prisonerInfoDao;
    }

    private static final String DOWNLOAD_PATH = "file/download/";
    private static final String SUFFIX = ".txt";

    /**
     * 导出数据
     *
     * @param importExport 导入导出属性
     * @param response     返回报文，用于获取返回流
     */
    public void exportData(ImportExport importExport, HttpServletResponse response) throws IOException {
        /* step1：生成导出文件 */
        String repository = systemParamService.getFileRepositoryRealPath();
        String fileName = UUID.randomUUID().toString() + SUFFIX;
        String datePath = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File file = new File(repository + "/" + datePath + "/" + fileName);
        if (!file.getParentFile().exists()) {
            boolean result = file.getParentFile().mkdirs();
            if (!result) {
                throw new SysException(ErrorMessage.CREATE_FILE_ERROR);
            }
        }
        String downloadUrl = DOWNLOAD_PATH + datePath + "/" + fileName;
        importExport.setDownloadUrl(downloadUrl);

        /* step2: 获取当前导入导出信息(importExport信息) */
        // 数据导出源环境（内网、外网或银行）
        Integer source = getEnvironmentCode();
        // 数据导出目标环境（内网、外网或银行）
        Integer target = importExport.getTarget();
        importExport.setType(ImportExport.EXPORT);
        importExport.setSource(getEnvironmentCode());

        /* step3: 获取导出数据 */
        Map<String, String> map = new HashMap<>();
        if (source == ImportExport.OUTER && target == ImportExport.INNER) {
            map = exportDataOuterToInter(importExport);
        } else if (source == ImportExport.OUTER && target == ImportExport.BANK) {
            map = exportDataOuterToBank(importExport);
        } else if (source == ImportExport.INNER && target == ImportExport.OUTER) {
            map = exportDataInnerToOuter(importExport);
        } else if (source == ImportExport.INNER && target == ImportExport.BANK) {
            map = exportDataInnerToBank(importExport);
        } else if (source == ImportExport.BANK && target == ImportExport.INNER) {
            map = exportDataBankToInner(importExport);
        } else if (source == ImportExport.BANK && target == ImportExport.OUTER) {
            map = exportDataBankToOuter(importExport);
        }
        /* step5: 将本次导出记录写入表 */
        Integer serialNumber = importExportDao.selectLastSerialNumber(importExport);
        if (serialNumber == null) {
            serialNumber = 1;
        } else {
            serialNumber++;
        }
        importExport.setSerialNumber(serialNumber);
        super.add(importExport);
        // 导入导出
        map.put(ImportExportKey.IMPORT_EXPORT, JSON.toJSONString(importExport));

        /* step6: 将对象写入文件 */
        String str = JSON.toJSONString(map);
        // JSON转加密串
        byte[] bytes = Base64.getEncoder().encode(str.getBytes("utf-8"));
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        out.write(bytes);
        out.flush();
        out.close();

        /* step7: 前端重定向到下载页面 */
        Organization organization = organizationDao.selectByPrimaryKey(importExport.getPrisonId());
        String filename = importExport.getSourceStr() + "-" + importExport.getTargetStr() + "-" + organization.getOrgName() + "-" + importExport.getSerialNumber();
        filename = new String(filename.getBytes("utf-8"), "ISO-8859-1");
        response.sendRedirect("/" + importExport.getDownloadUrl() + "?showName=" + filename);
    }

    /**
     * 导入数据
     *
     * @param file 导入的文件
     */
    @Transactional(rollbackFor = Exception.class)
    public void importData(MultipartFile file, User user) throws IOException {
        // step1: 判断文件有效性
        if (file == null) {
            throw new AppException(ErrorMessage.FILE_CAN_NOT_BE_NULL);
        }
        byte[] bytes = file.getBytes();
        try {
            bytes = Base64.getDecoder().decode(bytes);
        } catch (IllegalArgumentException ex) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }
        String json = new String(bytes);
        JSONObject jsonObject;
        try {
            jsonObject = JSON.parseObject(json);
        } catch (JSONException ex) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }

        // step2: 解析验证导入信息(importExport实体信息)
        if (!jsonObject.containsKey(ImportExportKey.IMPORT_EXPORT)) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }
        String importExportJson = (String) jsonObject.get(ImportExportKey.IMPORT_EXPORT);
        ImportExport importExport;
        try {
            importExport = JSON.parseObject(importExportJson, ImportExport.class);
            Integer target = getEnvironmentCode();
            if (!Objects.equals(target, importExport.getTarget())) {
                throw new AppException(ErrorMessage.IMPORT_FILE_TARGET_ERROR);
            }
            if (Objects.equals(target, ImportExport.INNER)) { // 导入到内网
                Long prisonId = systemParamService.getPrisonId();
                if (!Objects.equals(prisonId, importExport.getPrisonId())) {
                    throw new AppException(ErrorMessage.IMPORT_FILE_TARGET_ERROR);
                }
            }

            // 将导入信息写入表
            importExport.setType(ImportExport.IMPORT);
            importExport.setDownloadUrl(null);
            importExport.setCreateUser(user.getId());
            Integer lastSerialNumber = importExportDao.selectLastSerialNumber(importExport);
            lastSerialNumber = lastSerialNumber == null ? 0 : lastSerialNumber;
            if (lastSerialNumber >= importExport.getSerialNumber()) { // 重复导入
                throw new AppException(ErrorMessage.IMPORT_FILE_REPEAT);
            } else if ((lastSerialNumber + 1) < importExport.getSerialNumber()) {
                // 跳跃导入：跳过了某些序列号的数据
                throw new AppException(ErrorMessage.IMPORT_FILE_JUMP, (lastSerialNumber + 1));
            }
            super.add(importExport);
        } catch (JSONException ex) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }

        // step3: 导入商品信息
        if (jsonObject.containsKey(ImportExportKey.GOODS)) {
            if (importExport.getSource() == ImportExport.OUTER && importExport.getTarget() == ImportExport.INNER){
                importGoods(jsonObject.getJSONObject(ImportExportKey.GOODS));
            } else if (importExport.getSource() == ImportExport.INNER && importExport.getTarget() == ImportExport.BANK) {
                importGoodsInnerToBank(jsonObject.getJSONObject(ImportExportKey.GOODS));
            }
        }
        // step4: 导入发货信息
        if (jsonObject.containsKey(ImportExportKey.INVOICE)) {
            importInvoice(jsonObject.getJSONObject(ImportExportKey.INVOICE));
        }

        // step5: 导入组织信息
        if (jsonObject.containsKey(ImportExportKey.ORGANIZATION)) {
            importOrganization(jsonObject.getJSONObject(ImportExportKey.ORGANIZATION));
        }

        // step6: 导入供应商订单信息
        if (jsonObject.containsKey(ImportExportKey.ORDER_SUPPLIER)) {
            importOrderSupplier(jsonObject.getJSONObject(ImportExportKey.ORDER_SUPPLIER));
        }

        // step7: 导入缺货信息
        if (jsonObject.containsKey(ImportExportKey.GOODS_RETURN)) {
            if (importExport.getSource() == ImportExport.INNER && importExport.getTarget() == ImportExport.OUTER) {
                importGoodsReturnInnerToOuter(jsonObject.getJSONObject(ImportExportKey.GOODS_RETURN));
            } else if (importExport.getSource() == ImportExport.OUTER && importExport.getTarget() == ImportExport.INNER) {
                importGoodsReturnOuterToInner(jsonObject.getJSONObject(ImportExportKey.GOODS_RETURN));
            }
        }
        //step8:导入犯人资金流动记录
        if (jsonObject.containsKey(ImportExportKey.PRISONER_CAPITAL)){
            if (importExport.getSource() == ImportExport.INNER && importExport.getTarget() == ImportExport.BANK){
                importPrisonerCapitalInnerToBank(jsonObject.getJSONObject(ImportExportKey.PRISONER_CAPITAL));
            }else if (importExport.getSource() == ImportExport.BANK && importExport.getTarget() == ImportExport.INNER){
                importPrisonerCapitalBankToInner(jsonObject.getJSONObject(ImportExportKey.PRISONER_CAPITAL));
            }
        }
        //step9:导入犯人基本信息
        if (jsonObject.containsKey(ImportExportKey.PRISONER_BASIC)){
            importPrisonerBasicInnerToOut(jsonObject.getJSONObject(ImportExportKey.PRISONER_BASIC));
        }

        //step10:导入犯人信息或账户
        if (jsonObject.containsKey(ImportExportKey.PRISONER_INFO)){
            if (importExport.getSource() == ImportExport.INNER && importExport.getTarget() == ImportExport.BANK){
                importPrisonerInfoInnerToBank(jsonObject.getJSONObject(ImportExportKey.PRISONER_INFO));
            }else if (importExport.getSource() == ImportExport.BANK && importExport.getTarget() == ImportExport.INNER){
                importPrisonerInfoBankToInner(jsonObject.getJSONObject(ImportExportKey.PRISONER_INFO));
            }
        }

        //step9:导入账户余额
        if (jsonObject.containsKey(ImportExportKey.BALANCE)){
            importBalanceBankToInner(jsonObject.getJSONObject(ImportExportKey.BALANCE));
        }
    }

    //=============
    // 外网->内网
    private Map<String, String> exportDataOuterToInter(ImportExport importExport) throws IOException {
        Map<String, String> map = new HashMap<>();
        // 商品
        map.put(ImportExportKey.GOODS, exportGoods(importExport.getPrisonId()));
        // 发货单
        map.put(ImportExportKey.INVOICE, exportInvoice(importExport.getPrisonId()));
        // 组织信息
        map.put(ImportExportKey.ORGANIZATION, exportOrganization(importExport.getPrisonId()));
        // 缺货单
        map.put(ImportExportKey.GOODS_RETURN, exportGoodsReturnOuterToInner(importExport.getPrisonId()));
        return map;
    }

    // 外网->银行
    private Map<String, String> exportDataOuterToBank(ImportExport importExport) {
        Map<String, String> map = new HashMap<>();
        map.put("test", importExport.toString());
        return map;
    }

    // 内网->外网
    private Map<String, String> exportDataInnerToOuter(ImportExport importExport) {
        importExport.setPrisonId(systemParamService.getPrisonId());
        Map<String, String> map = new HashMap<>();
        // 供应商订单
        map.put(ImportExportKey.ORDER_SUPPLIER, exportOrderSupplier(importExport.getPrisonId()));
        // 缺货登记
        map.put(ImportExportKey.GOODS_RETURN, exportGoodsReturnInnerToOuter(importExport.getPrisonId()));
        //犯人基本信息
        map.put(ImportExportKey.PRISONER_BASIC,exportPrisonerBasicInnerToOut());
        return map;
    }

    // 内网->银行
    private Map<String, String> exportDataInnerToBank(ImportExport importExport) throws IOException {
        Map<String, String> map = new HashMap<>();
        importExport.setPrisonId(systemParamService.getPrisonId());
        map.put(ImportExportKey.PRISONER_CAPITAL,exportPrisonerCapitalInnerToBank());
        map.put(ImportExportKey.PRISONER_INFO,exportPrisonerInfoInnerToBank());
        map.put(ImportExportKey.GOODS,exportGoodsInnerToBank(importExport.getPrisonId()));
        return map;
    }

    // 银行->内网
    private Map<String, String> exportDataBankToInner(ImportExport importExport) {
        Map<String, String> map = new HashMap<>();
        map.put("test", importExport.toString());
        //扣款
        map.put(ImportExportKey.PRISONER_CAPITAL,exportPrisonerCapitalBankToInner());
        //银行账户
        map.put(ImportExportKey.PRISONER_INFO,exportPrisonerInfoBankToInner());
        //余额
        map.put(ImportExportKey.BALANCE,exportBalanceBankToInner());
        return map;
    }

    // 银行->外网
    private Map<String, String> exportDataBankToOuter(ImportExport importExport) {
        Map<String, String> map = new HashMap<>();
        map.put("test", importExport.toString());
        return map;
    }

    // 获取当前系统运行环境的编码
    public Integer getEnvironmentCode() {
        String environment = projectConfig.getEnvironment();
        if (Objects.equals(environment, "outer")) {
            return ImportExport.OUTER;
        } else if (Objects.equals(environment, "inner")) {
            return ImportExport.INNER;
        }else if (Objects.equals(environment, "bank")){
            return ImportExport.BANK;
        }else {
            throw new AppException(ErrorMessage.ENVIRONMENT_IS_NOT_DEFINED);
        }
    }

    // 二进制转字符串
    private static String byte2hex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        String tmp;
        for (byte aB : b) {
            tmp = Integer.toHexString(aB & 0XFF);
            if (tmp.length() == 1) {
                sb.append("0").append(tmp);
            } else {
                sb.append(tmp);
            }
        }
        return sb.toString();
    }

    // 字符串转二进制
    private static byte[] hex2byte(String str) {
        if (str == null)
            return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 == 1)
            return null;
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer.decode("0X" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }

    // 导出商品
    private String exportGoods(Long prisonId) throws IOException {
        Map<String, Object> map = new HashMap<>();

        // 上架商品列表
        GoodsPublishDetail goodsPublishDetail = new GoodsPublishDetail();
        goodsPublishDetail.setPrisonsId(prisonId);
        List<GoodsPublishDetail> goodsList = goodsPublishDetailDao.selectListForExport(goodsPublishDetail);
        map.put(ImportExportKey.GOODS_LIST, goodsList);
        // 商品类型
        GoodsType goodsType = new GoodsType();
        goodsType.setStatus(CommonStatus.VALID.getValue());
        List<GoodsType> goodsTypeList = goodsTypeDao.selectList(goodsType);
        map.put(ImportExportKey.GOODS_TYPE, goodsTypeList);
        // 商品图片
        List<Map<String, Object>> goodsImgList = new ArrayList<>();
        String repository = systemParamService.getFileRepositoryRealPath();
        for (GoodsPublishDetail goods : goodsList) {
            String goodsImg = goods.getGoodsImg();
            goodsImg = goodsImg.replace(DOWNLOAD_PATH, "");
            File file = new File(repository + "/" + goodsImg);
            if (file.exists()) {
                // 将图片转换成字符串
                FileInputStream fis = new FileInputStream(file);
                byte[] bytes = new byte[fis.available()];
                fis.read(bytes);
                fis.close();
                String imgStr = byte2hex(bytes);
                Map<String, Object> goodsImgFile = new HashMap<>();
                goodsImgFile.put("fileName", goodsImg);
                goodsImgFile.put("fileByte", imgStr);
                goodsImgList.add(goodsImgFile);
            }
        }
        map.put(ImportExportKey.GOODS_IMG, goodsImgList);
        return JSON.toJSONString(map);
    }

    // 导入商品
    private void importGoods(JSONObject jsonObject) throws IOException {
        try {
            if (jsonObject.containsKey(ImportExportKey.GOODS_LIST)) {
                String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_LIST).toString();
                List<GoodsPublishDetail> goodsList = JSON.parseArray(jsonArrayStr, GoodsPublishDetail.class);
                for (GoodsPublishDetail goods : goodsList) {
                    goods.setGoodsStatus(GoodsPublicStatus.PUBLISH.getValue());
                }
                goodsPublishDetailDao.deleteAll();
                if (goodsList.size() != 0) {
                    goodsPublishDetailDao.batchInsert(goodsList);
                }

                List<GoodsHistoryDetail> goodsHistoryDetailList = new ArrayList<>();
                for (GoodsPublishDetail goodsPublishDetail: goodsList) {
                    GoodsHistoryDetail goodsHistoryDetail=new GoodsHistoryDetail();
                    goodsHistoryDetail.setId(baseIdWorker.createId());
                    goodsHistoryDetail.setGoodsId(goodsPublishDetail.getId());
                    goodsHistoryDetail.setOrgId(goodsPublishDetail.getOrgId());
                    goodsHistoryDetail.setGoodsName(goodsPublishDetail.getGoodsName());
                    goodsHistoryDetail.setGoodsType(goodsPublishDetail.getGoodsType());
                    goodsHistoryDetail.setGoodsBarCode(goodsPublishDetail.getGoodsBarCode());
                    goodsHistoryDetail.setGoodsMarketPrice(goodsPublishDetail.getGoodsMarketPrice());
                    goodsHistoryDetail.setGoodsSellPrice(goodsPublishDetail.getGoodsSellPrice());
                    goodsHistoryDetail.setGoodsSettlementPrice(goodsPublishDetail.getGoodsSettlementPrice());
                    goodsHistoryDetail.setGoodsSpec(goodsPublishDetail.getGoodsSpec());
                    goodsHistoryDetail.setGoodsUnit(goodsPublishDetail.getGoodsUnit());
                    goodsHistoryDetail.setGoodsImg(goodsPublishDetail.getGoodsImg());
                    goodsHistoryDetail.setGoodsStatus(goodsPublishDetail.getGoodsStatus());
                    goodsHistoryDetail.setBoxSpec(goodsPublishDetail.getBoxSpec());
                    goodsHistoryDetail.setCreateTime(new Date());
                    goodsHistoryDetail.setUpdateTime(new Date());
                    goodsHistoryDetailList.add(goodsHistoryDetail);
                }
                if (goodsHistoryDetailList.size() != 0) {
                    goodsHistoryDetailDao.batchInsert(goodsHistoryDetailList);
                }
            }
            if (jsonObject.containsKey(ImportExportKey.GOODS_TYPE)) {
                String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_TYPE).toString();
                List<GoodsType> goodsTypeList = JSON.parseArray(jsonArrayStr, GoodsType.class);
                goodsTypeDao.deleteAll();
                goodsTypeDao.batchInsert(goodsTypeList);
            }
            if (jsonObject.containsKey(ImportExportKey.GOODS_IMG)) {
                JSONArray jsonArray = jsonObject.getJSONArray(ImportExportKey.GOODS_IMG);
                for (Object obj : jsonArray) {
                    JSONObject jsonObj = (JSONObject) obj;
                    String fileName = jsonObj.getString("fileName");
                    String fileByte = jsonObj.getString("fileByte");
                    byte[] imgByte = hex2byte(fileByte);
                    String repository = systemParamService.getFileRepositoryRealPath();
                    File file = new File(repository + "/" + fileName);
                    if (!file.getParentFile().exists()) {
                        boolean success = file.getParentFile().mkdirs();
                        if (!success) {
                            System.out.println("error to create file");
                        }
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(imgByte);
                    fos.flush();
                    fos.close();
                }
            }
        } catch (JSONException ex) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }
    }

    // 导出发货单
    private String exportInvoice(Long prisonId) {
        Map<String, Object> map = new HashMap<>();
        Invoice invoice = new Invoice();
        invoice.setAccountPrisons(prisonId);
        invoice.setStatus(InvoiceStatus.FINISH.getValue());
        List<Invoice> invoiceList = invoiceDao.selectList(invoice);
        map.put(ImportExportKey.INVOICE_LIST, invoiceList);
        InvoiceDetail invoiceDetail = new InvoiceDetail();
        invoiceDetail.setAccountPrisons(prisonId);
        List<InvoiceDetail> invoiceDetailList = invoiceDetailDao.selectList(invoiceDetail);
        map.put(ImportExportKey.INVOICE_DETAIL_LIST, invoiceDetailList);
        //更新发货单状态为已导入内网
        List<Long> longList=new ArrayList<>();
        for (Invoice invoice1:invoiceList){
            longList.add(invoice1.getId());
        }
        if(longList.size()>0){
            invoiceDao.batchUpdateStatus(InvoiceStatus.PENDING_AUDIT.getValue(),longList);
        }
        return JSON.toJSONString(map);
    }

    // 导入发货单
    private void importInvoice(JSONObject jsonObject) {
        if (jsonObject.containsKey(ImportExportKey.INVOICE_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.INVOICE_LIST).toString();
            List<Invoice> invoiceList = JSON.parseArray(jsonArrayStr, Invoice.class);
            Iterator<Invoice> iterator = invoiceList.iterator();
            while (iterator.hasNext()) {
                Invoice invoice = iterator.next();
                Invoice check = invoiceDao.selectByPrimaryKey(invoice.getId());
                if (check != null) { // 之前导入过
                    iterator.remove();
                }
            }
            if (invoiceList.size() != 0) {
                invoiceDao.batchInsert(invoiceList);
            }
        }
        if (jsonObject.containsKey(ImportExportKey.INVOICE_DETAIL_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.INVOICE_DETAIL_LIST).toString();
            List<InvoiceDetail> invoiceDetailList = JSON.parseArray(jsonArrayStr, InvoiceDetail.class);
            Iterator<InvoiceDetail> iterator = invoiceDetailList.iterator();
            while (iterator.hasNext()) {
                InvoiceDetail invoiceDetail = iterator.next();
                InvoiceDetail check = invoiceDetailDao.selectByPrimaryKey(invoiceDetail.getId());
                if (check != null) {
                    iterator.remove();
                }
            }
            if (invoiceDetailList.size() != 0) {
                invoiceDetailDao.batchInsert(invoiceDetailList);
            }
        }
    }

    // 导出组织信息
    private String exportOrganization(Long prisonId) {
        Map<String, Object> map = new HashMap<>();
        Organization prison = organizationDao.selectByPrimaryKey(prisonId);
        map.put(ImportExportKey.PRISON_LIST, prison);
        RelationSupplierPrison relationSupplierPrison = new RelationSupplierPrison();
        relationSupplierPrison.setPrisonId(prisonId);
        List<RelationSupplierPrison> relationSupplierPrisonList = relationSupplierPrisonDao.selectList(relationSupplierPrison);
        map.put(ImportExportKey.RELATION_SUPPLIER_PRISON, relationSupplierPrisonList);
        List<Organization> supplierList = new ArrayList<>();
        for (RelationSupplierPrison relation : relationSupplierPrisonList) {
            Organization supplier = organizationDao.selectByPrimaryKey(relation.getSupplierId());
            supplierList.add(supplier);
        }
        map.put(ImportExportKey.SUPPLIER_LIST, supplierList);
        return JSON.toJSONString(map);
    }

    // 导入组织信息
    private void importOrganization(JSONObject jsonObject) {
        if (jsonObject.containsKey(ImportExportKey.PRISON_LIST)) {
            String prisonStr = jsonObject.getJSONObject(ImportExportKey.PRISON_LIST).toString();
            Organization prison = JSON.parseObject(prisonStr, Organization.class);
            Organization check = organizationDao.selectByPrimaryKey(prison.getId());
            if (check == null) {
                organizationDao.insert(prison);
            } else {
                organizationDao.update(prison);
            }
        }
        if (jsonObject.containsKey(ImportExportKey.SUPPLIER_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.SUPPLIER_LIST).toString();
            List<Organization> supplierList = JSON.parseArray(jsonArrayStr, Organization.class);
            for (Organization supplier : supplierList) {
                Organization check = organizationDao.selectByPrimaryKey(supplier.getId());
                if (check == null) {
                    organizationDao.insert(supplier);
                } else {
                    organizationDao.update(supplier);
                }
            }
        }
        if (jsonObject.containsKey(ImportExportKey.RELATION_SUPPLIER_PRISON)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.RELATION_SUPPLIER_PRISON).toString();
            List<RelationSupplierPrison> relationSupplierPrisonList = JSON.parseArray(jsonArrayStr, RelationSupplierPrison.class);
            relationSupplierPrisonDao.deleteAll();
            relationSupplierPrisonDao.batchInsert(relationSupplierPrisonList);
        }
    }

    // 导出供应商订单
    private String exportOrderSupplier(Long prisonId) {
        Map<String, Object> map = new HashMap<>();

        // 供应商订单列表
        OrderSupplier orderSupplier = new OrderSupplier();
        orderSupplier.setAccountPrisons(prisonId);
        orderSupplier.setStatus(OrderSupplierStatus.PENDINGAUDIR.getValue());
        List<OrderSupplier> orderSupplierList = orderSupplierDao.selectList(orderSupplier);
        for (OrderSupplier os : orderSupplierList) {
            os.setStatus(OrderSupplierStatus.AUTIDED.getValue());
            orderSupplierDao.update(os);
        }
        map.put(ImportExportKey.ORDER_SUPPLIER_LIST, orderSupplierList);

        // 供应商订单详情列表
        List<OrderSupplierDetail> orderSupplierDetailList = new ArrayList<>();
        for (OrderSupplier temp : orderSupplierList) {
            List<OrderSupplierDetail> list = orderSupplierDetailDao.selectListDetail(temp.getId());
            orderSupplierDetailList.addAll(list);
        }
        map.put(ImportExportKey.ORDER_SUPPLIER_DETAIL_LIST, orderSupplierDetailList);
        return JSON.toJSONString(map);
    }

    // 导入供应商订单
    private void importOrderSupplier(JSONObject jsonObject) {
        if (jsonObject.containsKey(ImportExportKey.ORDER_SUPPLIER_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.ORDER_SUPPLIER_LIST).toString();
            List<OrderSupplier> orderSupplierList = JSON.parseArray(jsonArrayStr, OrderSupplier.class);
            for (OrderSupplier orderSupplier : orderSupplierList) {
                orderSupplier.setStatus(OrderSupplierStatus.AUTIDED.getValue());
                orderSupplierDao.insert(orderSupplier);
            }
        }
        if (jsonObject.containsKey(ImportExportKey.ORDER_SUPPLIER_DETAIL_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.ORDER_SUPPLIER_DETAIL_LIST).toString();
            List<OrderSupplierDetail> orderSupplierDetailList = JSON.parseArray(jsonArrayStr, OrderSupplierDetail.class);
            for (OrderSupplierDetail orderSupplierDetail : orderSupplierDetailList) {
                orderSupplierDetailDao.insert(orderSupplierDetail);
            }
        }
    }

    // 导出缺货登记(内网->外网)
    private String exportGoodsReturnInnerToOuter(Long prisonId) {
        Map<String, Object> map = new HashMap<>();
        GoodsReturn goodsReturn = new GoodsReturn();
        goodsReturn.setPrisonerId(prisonId);
        // 查询待导出外网
        goodsReturn.setStatus(GoodsReturnStatus.REPLENISHMENT.getValue());
        List<GoodsReturn> goodsReturnList = goodsReturnDao.selectList(goodsReturn);
        for (GoodsReturn gr: goodsReturnList) {
            gr.setStatus(GoodsReturnStatus.PART_FINISH.getValue());
            goodsReturnDao.update(gr);
        }
        map.put(ImportExportKey.GOODS_RETURN_LIST, goodsReturnList);
        return JSON.toJSONString(map);
    }

    // 导入缺货登记(内网->外网)
    private void importGoodsReturnInnerToOuter(JSONObject jsonObject) {
        if (jsonObject.containsKey(ImportExportKey.GOODS_RETURN_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_RETURN_LIST).toString();
            List<GoodsReturn> goodsReturnList = JSON.parseArray(jsonArrayStr, GoodsReturn.class);
            for (GoodsReturn gr : goodsReturnList) {
                gr.setStatus(GoodsReturnStatus.PENDING_BACK_GOODS.getValue());
                goodsReturnDao.insert(gr);
                //修改状态为缺货状态
                Invoice invoice = invoiceDao.selectByPrimaryKey(gr.getInvoiceId());
                //如果以生成结算单，则不许改发货单状态
                if (invoice.getStatus().equals(InvoiceStatus.SETTLEMENT.getValue())){
                    invoice.setStatus(InvoiceStatus.OUT_OF_STOCK.getValue());
                    invoiceDao.update(invoice);
                }
            }
        }
    }

    // 导出缺货登记(外网->内网)
    private String exportGoodsReturnOuterToInner(Long prisonId) {
        Map<String, Object> map = new HashMap<>();
        GoodsReturn goodsReturn = new GoodsReturn();
        goodsReturn.setPrisonerId(prisonId);
        // 查询待导入内网
        goodsReturn.setStatus(GoodsReturnStatus.FINISH_BACK_GOODS.getValue());
        List<GoodsReturn> goodsReturnList = goodsReturnDao.selectList(goodsReturn);
        for (GoodsReturn gr: goodsReturnList) {
            gr.setStatus(GoodsReturnStatus.SURE_GOODS_RETURN.getValue());
            goodsReturnDao.update(gr);
            //修改状态为已收货状态
            Invoice invoice = invoiceDao.selectByPrimaryKey(gr.getInvoiceId());
            //如果以生成结算单，则不许改发货单状态
            if (invoice.getStatus().equals(InvoiceStatus.SETTLEMENT.getValue())){
                invoice.setStatus(InvoiceStatus.FINISH.getValue());
                invoiceDao.update(invoice);
            }
        }
        map.put(ImportExportKey.GOODS_RETURN_LIST, goodsReturnList);
        return JSON.toJSONString(map);
    }

    // 导入缺货登记(外网->内网)
    private void importGoodsReturnOuterToInner(JSONObject jsonObject) {
        if (jsonObject.containsKey(ImportExportKey.GOODS_RETURN_LIST)) {
            String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_RETURN_LIST).toString();
            List<GoodsReturn> goodsReturnList = JSON.parseArray(jsonArrayStr, GoodsReturn.class);
            for (GoodsReturn gr : goodsReturnList) {
                gr.setStatus(GoodsReturnStatus.PENDING_GOODS_RETURN.getValue());
                goodsReturnDao.update(gr);
            }
        }
    }

    //导出犯人信息(内网→银行)
    private String exportPrisonerInfoInnerToBank(){
        Map<String, Object> map = new HashMap<>();
        //犯人信息
        PrisonerInfo prisonerInfo = new PrisonerInfo();
        prisonerInfo.setBankStatus(PrisonerInfoBankStatus.DELIVERY_BANK.getValue());
        List<PrisonerInfo> prisonerInfos = prisonerInfoDao.selectList(prisonerInfo);
        map.put(ImportExportKey.PRISONER_INFO_LIST,prisonerInfos);
        for (PrisonerInfo temp:prisonerInfos){
            temp.setBankStatus(PrisonerInfoBankStatus.FINISH_BANK.getValue());
            prisonerInfoDao.update(temp);
        }
        return JSON.toJSONString(map);
    }

    //导入犯人信息(内网→银行)
    private void importPrisonerInfoInnerToBank(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.PRISONER_INFO_LIST)){
            String toString = jsonObject.getJSONArray(ImportExportKey.PRISONER_INFO_LIST).toString();
            List<PrisonerInfo> prisonerInfos = JSON.parseArray(toString, PrisonerInfo.class);
            for (PrisonerInfo prisonerInfo:prisonerInfos){
                //prisonerInfo.setBankStatus(PrisonerInfoBankStatus.STAY_OPEN.getValue());
                prisonerInfoDao.insert(prisonerInfo);
            }
        }
    }

    //导出犯人资金流动记录(内网→银行)
    private String exportPrisonerCapitalInnerToBank(){
        Map<String, Object> map = new HashMap<>();
        //犯人资金
        PrisonerCapitalFlow prisonerCapitalFlow=new PrisonerCapitalFlow();
        prisonerCapitalFlow.setStatus(PrisonerCapitalFlowStatus.DELIVERY_BANK.getValue());
        List<PrisonerCapitalFlow> prisonerCapitalFlows = prisonerCapitalFlowDao.selectList(prisonerCapitalFlow);
        map.put(ImportExportKey.PRISONER_CAPITAL_LIST,prisonerCapitalFlows);
        for (PrisonerCapitalFlow temp:prisonerCapitalFlows){
            temp.setStatus(PrisonerCapitalFlowStatus.FINISH_BANK.getValue());
            prisonerCapitalFlowDao.update(temp);
        }
        FlowType flowType = new FlowType();
        flowType.setStatus(CommonStatus.VALID.getValue());
        List<FlowType> flowTypes = flowTypeDao.selectList(flowType);
        map.put(ImportExportKey.FLOW_TYPE,flowTypes);
        return JSON.toJSONString(map);
    }
    //导入犯人资金流动记录(内网→银行)
    private void importPrisonerCapitalInnerToBank(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.PRISONER_CAPITAL_LIST)){
            String toString = jsonObject.getJSONArray(ImportExportKey.PRISONER_CAPITAL_LIST).toString();
            List<PrisonerCapitalFlow> prisonerCapitalFlows = JSON.parseArray(toString, PrisonerCapitalFlow.class);
            for (PrisonerCapitalFlow prisonerCapitalFlow:prisonerCapitalFlows){
                //prisonerCapitalFlow.setStatus(PrisonerCapitalFlowStatus.DELIVER_INNER.getValue());
                prisonerCapitalFlowDao.insert(prisonerCapitalFlow);
            }
        }
        if (jsonObject.containsKey(ImportExportKey.FLOW_TYPE)){
            String toString = jsonObject.getJSONArray(ImportExportKey.FLOW_TYPE).toString();
            List<FlowType> flowTypes = JSON.parseArray(toString, FlowType.class);
            flowTypeDao.deleteAll();
            flowTypeDao.batchInsert(flowTypes);
        }

    }


/*    //导出犯人 账户信息(银行→内网)
    private String exportPrisonerInfoBankToInner(){
        Map<String, Object> map = new HashMap<>();
        List<PrisonerInfo> list=new ArrayList<>();
        PrisonerInfo prisonerInfo=new PrisonerInfo();
        prisonerInfo.setBankStatus(PrisonerInfoBankStatus.SUCCESS_NOBACK.getValue());
        List<PrisonerInfo> prisonerInfo1 = prisonerInfoDao.selectList(prisonerInfo);
        list.addAll(prisonerInfo1);
        for (PrisonerInfo temp:prisonerInfo1){
            temp.setBankStatus(PrisonerInfoBankStatus.SUCCESS_BACK.getValue());
            prisonerInfoDao.update(temp);
        }
        prisonerInfo.setStatus(PrisonerInfoBankStatus.FAIL_NOBACK.getValue());
        List<PrisonerInfo> prisonerInfo2 = prisonerInfoDao.selectList(prisonerInfo);
        list.addAll(prisonerInfo2);
        for (PrisonerInfo temp:prisonerInfo2){
            temp.setBankStatus(PrisonerInfoBankStatus.FAIL_BACK.getValue());
            prisonerInfoDao.update(temp);
        }
        map.put(ImportExportKey.PRISONER_INFO_LIST,list);
        return JSON.toJSONString(map);
    }*/

    //导出犯人 账户信息(银行→内网)
    private String exportPrisonerInfoBankToInner(){
        Map<String, Object> map = new HashMap<>();
        List<PrisonerAccount> list=new ArrayList<>();
        PrisonerAccount prisonerAccount=new PrisonerAccount();
        prisonerAccount.setStatus(PrisonerAccountStatus.SUCCESS_NOBACK.getValue());
        List<PrisonerAccount> prisonerInfo1 = prisonerAccountDao.selectList(prisonerAccount);
        list.addAll(prisonerInfo1);
        for (PrisonerAccount temp:prisonerInfo1){
            temp.setStatus(PrisonerAccountStatus.SUCCESS_BACK.getValue());
            prisonerAccountDao.update(temp);
        }
        prisonerAccount.setStatus(PrisonerAccountStatus.FAIL_NOBACK.getValue());
        List<PrisonerAccount> prisonerInfo2 = prisonerAccountDao.selectList(prisonerAccount);
        list.addAll(prisonerInfo2);
        for (PrisonerAccount temp:prisonerInfo2){
            temp.setStatus(PrisonerAccountStatus.FAIL_BACK.getValue());
            prisonerAccountDao.update(temp);
        }
        map.put(ImportExportKey.PRISONER_INFO_LIST,list);
        return JSON.toJSONString(map);
    }

    //导入犯人 账户信息(银行→内网)
    private void importPrisonerInfoBankToInner(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.PRISONER_INFO_LIST)){
            String toString = jsonObject.getJSONArray(ImportExportKey.PRISONER_INFO_LIST).toString();
            List<PrisonerAccount> prisonerAccounts = JSON.parseArray(toString, PrisonerAccount.class);
            //开户成功 插入账户表 更新犯人信息表状态
            for (PrisonerAccount prisonerAccount:prisonerAccounts){
                if(prisonerAccount.getStatus() == PrisonerAccountStatus.SUCCESS_BACK.getValue()){
                    //插入账户表
                    // prisonerAccount.setStatus(PrisonerAccountStatus.SUCCESS_BACK.getValue());
                    prisonerAccountDao.insert(prisonerAccount);
                    //更新犯人信息表状态
                    PrisonerInfo temp = prisonerInfoDao.selectByPrimaryKey(prisonerAccount.getId());
                    temp.setBankStatus(PrisonerInfoBankStatus.SUCCESS_BACK.getValue());
                    prisonerInfoDao.update(temp);
                }else{
                    //开户失败  更新犯人信息表状态
                    PrisonerInfo temp = prisonerInfoDao.selectByPrimaryKey(prisonerAccount.getId());
                    temp.setBankStatus(PrisonerInfoBankStatus.FAIL_BACK.getValue());
                    prisonerInfoDao.update(temp);
                }
            }


        }
    }


    //导出犯人账户余额(银行→内网)
    private String exportBalanceBankToInner(){
        Map<String, Object> map = new HashMap<>();
        PrisonerAccount prisonerAccount=new PrisonerAccount();
        List<PrisonerAccount> prisonerAccounts = prisonerAccountDao.selectList(prisonerAccount);
        map.put(ImportExportKey.BALANCE,prisonerAccounts);
        return JSON.toJSONString(map);
    }

    //导入犯人账户余额(银行→内网)
    private void importBalanceBankToInner(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.BALANCE)){
            String toString = jsonObject.getJSONArray(ImportExportKey.BALANCE).toString();
            List<PrisonerAccount> prisonerAccounts = JSON.parseArray(toString, PrisonerAccount.class);
            for (PrisonerAccount temp:prisonerAccounts){
                //更新余额
                PrisonerAccount prisonerAccount = prisonerAccountDao.selectByPrimaryKey(temp.getId());
                if(null != prisonerAccount){
                    prisonerAccount.setBalance(temp.getBalance());
                    prisonerAccount.setTotalBalance(temp.getTotalBalance());
                    prisonerAccountDao.update(prisonerAccount);
                }

            }
        }
    }


    //导出犯人资金流动记录(银行→内网)
    private String exportPrisonerCapitalBankToInner(){
        Map<String, Object> map = new HashMap<>();
        List<PrisonerCapitalFlow> list=new ArrayList<>();
        PrisonerCapitalFlow prisonerCapitalFlow=new PrisonerCapitalFlow();
        prisonerCapitalFlow.setStatus(PrisonerCapitalFlowStatus.SUCCESS_DELIVERY_INNER.getValue());
        List<PrisonerCapitalFlow> successPrisonerCapitalFlows = prisonerCapitalFlowDao.selectList(prisonerCapitalFlow);
        list.addAll(successPrisonerCapitalFlows);
        for (PrisonerCapitalFlow temp:successPrisonerCapitalFlows){
            temp.setStatus(PrisonerCapitalFlowStatus.SUCCESS.getValue());
            prisonerCapitalFlowDao.update(temp);
        }
        prisonerCapitalFlow.setStatus(PrisonerCapitalFlowStatus.FAIL_DELIVERY_INNER.getValue());
        List<PrisonerCapitalFlow> failPrisonerCapitalFlows = prisonerCapitalFlowDao.selectList(prisonerCapitalFlow);
        list.addAll(failPrisonerCapitalFlows);
        for (PrisonerCapitalFlow temp:failPrisonerCapitalFlows){
            temp.setStatus(PrisonerCapitalFlowStatus.FAIL.getValue());
            prisonerCapitalFlowDao.update(temp);
        }
        map.put(ImportExportKey.PRISONER_CAPITAL_LIST,list);
        return JSON.toJSONString(map);
    }
    //导入犯人资金流动记录(银行→内网)
    private void importPrisonerCapitalBankToInner(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.PRISONER_CAPITAL_LIST)){
            String toString = jsonObject.getJSONArray(ImportExportKey.PRISONER_CAPITAL_LIST).toString();
            List<PrisonerCapitalFlow> prisonerCapitalFlows = JSON.parseArray(toString, PrisonerCapitalFlow.class);
            for (PrisonerCapitalFlow prisonerCapitalFlow:prisonerCapitalFlows){
                PrisonerCapitalFlow temp = prisonerCapitalFlowDao.selectByPrimaryKey(prisonerCapitalFlow.getId());
                temp.setStatus(prisonerCapitalFlow.getStatus());
                prisonerCapitalFlowDao.update(temp);
            }
        }
    }
    //导出商品信息(内网→银行)
    private String exportGoodsInnerToBank(Long prisonId)throws IOException{
        Map<String, Object> map = new HashMap<>();
        // 上架商品列表
        GoodsPublishDetail goodsPublishDetail = new GoodsPublishDetail();
        goodsPublishDetail.setPrisonsId(prisonId);
        goodsPublishDetail.setGoodsStatus(GoodsPublicStatus.PUBLISH.getValue());
        List<GoodsPublishDetail> list = goodsPublishDetailDao.selectList(goodsPublishDetail);
        map.put(ImportExportKey.GOODS_LIST, list);
        // 商品类型
        GoodsType goodsType = new GoodsType();
        goodsType.setStatus(CommonStatus.VALID.getValue());
        List<GoodsType> goodsTypeList = goodsTypeDao.selectList(goodsType);
        map.put(ImportExportKey.GOODS_TYPE, goodsTypeList);
        // 商品图片
        List<Map<String, Object>> goodsImgList = new ArrayList<>();
        String repository = systemParamService.getFileRepositoryRealPath();
        for (GoodsPublishDetail goods : list) {
            String goodsImg = goods.getGoodsImg();
            goodsImg = goodsImg.replace(DOWNLOAD_PATH, "");
            File file = new File(repository + "/" + goodsImg);
            if (file.exists()) {
                // 将图片转换成字符串
                FileInputStream fis = new FileInputStream(file);
                byte[] bytes = new byte[fis.available()];
                fis.read(bytes);
                fis.close();
                String imgStr = byte2hex(bytes);
                Map<String, Object> goodsImgFile = new HashMap<>();
                goodsImgFile.put("fileName", goodsImg);
                goodsImgFile.put("fileByte", imgStr);
                goodsImgList.add(goodsImgFile);
            }
        }
        map.put(ImportExportKey.GOODS_IMG, goodsImgList);
        return JSON.toJSONString(map);
    }
    //导入商品信息(内网→银行)
    private void  importGoodsInnerToBank(JSONObject jsonObject) throws IOException{
        try {
            if (jsonObject.containsKey(ImportExportKey.GOODS_LIST)) {
                String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_LIST).toString();
                List<GoodsPublishDetail> goodsList = JSON.parseArray(jsonArrayStr, GoodsPublishDetail.class);
                goodsPublishDetailDao.deleteAll();
                if (goodsList.size() != 0) {
                    goodsPublishDetailDao.batchInsert(goodsList);
                }
            }
            if (jsonObject.containsKey(ImportExportKey.GOODS_TYPE)) {
                String jsonArrayStr = jsonObject.getJSONArray(ImportExportKey.GOODS_TYPE).toString();
                List<GoodsType> goodsTypeList = JSON.parseArray(jsonArrayStr, GoodsType.class);
                goodsTypeDao.deleteAll();
                goodsTypeDao.batchInsert(goodsTypeList);
            }
            if (jsonObject.containsKey(ImportExportKey.GOODS_IMG)) {
                JSONArray jsonArray = jsonObject.getJSONArray(ImportExportKey.GOODS_IMG);
                for (Object obj : jsonArray) {
                    JSONObject jsonObj = (JSONObject) obj;
                    String fileName = jsonObj.getString("fileName");
                    String fileByte = jsonObj.getString("fileByte");
                    byte[] imgByte = hex2byte(fileByte);
                    String repository = systemParamService.getFileRepositoryRealPath();
                    File file = new File(repository + "/" + fileName);
                    if (!file.getParentFile().exists()) {
                        boolean success = file.getParentFile().mkdirs();
                        if (!success) {
                            System.out.println("error to create file");
                        }
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(imgByte);
                    fos.flush();
                    fos.close();
                }
            }
        } catch (JSONException ex) {
            throw new AppException(ErrorMessage.IMPORT_FILE_ERROR);
        }
    }
    //犯人基本信息导出(内网→外网)
    private String exportPrisonerBasicInnerToOut(){
        Map<String, Object> map = new HashMap<>();
        List<PrisonerBasic> list= new ArrayList<>();
        List<PrisonerAccount> prisonerAccounts = prisonerAccountDao.selectList(new PrisonerAccount());
        for (PrisonerAccount prisonerAccount:prisonerAccounts){
            PrisonerBasic prisonerBasic=new PrisonerBasic();
            prisonerBasic.setId(prisonerAccount.getId());
            prisonerBasic.setBankCard(prisonerAccount.getBankCard());
            list.add(prisonerBasic);
        }
        map.put(ImportExportKey.PRISONER_BASIC_LIST,list);
        return JSON.toJSONString(map);
    }
    //犯人基本信息导入(内网→外网)
    private void importPrisonerBasicInnerToOut(JSONObject jsonObject){
        if (jsonObject.containsKey(ImportExportKey.PRISONER_BASIC_LIST)){
            String toString = jsonObject.getJSONArray(ImportExportKey.PRISONER_BASIC_LIST).toString();
            List<PrisonerBasic> list = JSON.parseArray(toString, PrisonerBasic.class);
            for (PrisonerBasic prisonerBasic:list){
                PrisonerBasic temp = prisonerBasicDao.selectByPrimaryKey(prisonerBasic.getId());
                //如果已经导入过的就不需要再导入
                if(temp == null){
                    prisonerBasicDao.insert(prisonerBasic);
                }
            }
        }
    }
}
